package cn.yunzhisheng.vui.assistant.tv.session;

import java.util.Locale;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.ViewFlipper;
import cn.yunzhisheng.common.JsonTool;
import cn.yunzhisheng.common.net.Network;
import cn.yunzhisheng.common.util.LogUtil;
import cn.yunzhisheng.vui.assistant.preference.SessionPreference;
import cn.yunzhisheng.vui.assistant.tv.WindowService;
import cn.yunzhisheng.vui.assistant.tv.talk.ITalkServicePresentorListener;
import cn.yunzhisheng.vui.assistant.tv.IVuiVoiceCallBack;
import cn.yunzhisheng.vui.assistant.tv.talk.TalkServicePresentor;
import cn.yunzhisheng.vui.assistant.tv.view.GloblFloatView;
import cn.yunzhisheng.vui.assistant.tv.view.VoiceMode;

@SuppressLint("HandlerLeak")
public class SessionManager {
    private static final String TAG = "SessionManager";

    public static final int TASK_DELAY_KEY_TTS_END = 100;
    public static final int TASK_DELAY_KEY_SESSION_END = 101;
    public static final int TASK_DELAY_VALUE_RESET_TIMER = 1;

    private static final String BACK_PROTOCAL = "{\"service\":\"DOMAIN_KEY\",\"key\":\"back\"}";

    private WindowService mContext = null;
    // private ViewFlipper mViewFlipper = null;

    // private FunctionContainer mFunctionContainer = null;
    // private SessionContainer mFunctionViewContainer = null;
    // private SessionContainer mSessionViewContainer = null;
    private boolean mNeedAutoStart = true;
    private TalkServicePresentor mTalkServicePresentor = null;
    // private BaseSession mCurrentSession = null;
    private DelayTaskArray mDelayTaskArray = new DelayTaskArray();
    private PopupWindow mPopupWindow = null;
    private ISessionManagerListener mListener;
    private GloblFloatView micFloatView;

    private Handler mSessionManagerHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            LogUtil.d(TAG, "handleMessage:" + msg);
            switch (msg.what) {
            case SessionPreference.MESSAGE_START_TALK:
                startTalk();
                break;
            case SessionPreference.MESSAGE_STOP_TALK:
                stopTalk();
                break;
            case SessionPreference.MESSAGE_CANCEL_TALK:
                cancelTalk();
                break;
            case SessionPreference.MESSAGE_SESSION_CANCEL:
                // if (mCurrentSession != null) {
                // mCurrentSession.release();
                // mCurrentSession = null;
                // }
                int value = mDelayTaskArray.pop(TASK_DELAY_KEY_SESSION_END);
                if (value != 0) {
                    handleDelayTask(value);
                }
                break;
            case SessionPreference.MESSAGE_SESSION_DONE:
                // mSessionViewContainer.clearTemporaryViews();
                // if (mCurrentSession != null) {
                // mCurrentSession.release();
                // mCurrentSession = null;
                // }
                value = mDelayTaskArray.pop(TASK_DELAY_KEY_SESSION_END);
                if (value != 0) {
                    handleDelayTask(value);
                }
                break;
            case SessionPreference.MESSAGE_REQUEST_MUSIC_START:
                // if (mListener != null) {
                // if (mCurrentSession instanceof MusicShowSession) {
                // mListener
                // .onMusicSearchDone(((MusicShowSession) mCurrentSession)
                // .getPlayList());
                // }
                // }
                break;
            case SessionPreference.MESSAGE_REQUEST_PLAY_TTS:
                mTalkServicePresentor.playTTS((String) msg.obj);
                break;
            case SessionPreference.MESSAGE_REQUEST_CANCEL_TTS:
                mTalkServicePresentor.stopTTS();
                break;
            case SessionPreference.MESSAGE_REQUEST_RESET_TIMER:
                if (mListener != null) {
                    mListener.onResetTimer();
                }
                break;
            case SessionPreference.MESSAGE_REQUEST_CANCEL_TIMER:
                if (mListener != null) {
                    mListener.onCancelTimer();
                }
                break;
            case SessionPreference.MESSAGE_NEW_PROTOCAL:
                String strProtocolString = (String) msg.obj;
                createSession(strProtocolString);
                break;
            case SessionPreference.MESSAGE_TASK_DELY:
                mDelayTaskArray.put(msg.arg1, msg.arg2);
                break;
            case SessionPreference.MESSAGE_ADD_ANSWER_TEXT:
                String text = (String) msg.obj;
                // mSessionViewContainer.addAnswerView(text);
                break;
            case SessionPreference.MESSAGE_ADD_ANSWER_VIEW:
                View view = (View) msg.obj;
                // mSessionViewContainer.addSessionView(view, false);
                break;
            case SessionPreference.MESSAGE_ADD_QUESTION_TEXT:
                // mSessionViewContainer.addQustionView((String) msg.obj);
                break;
            case SessionPreference.MESSAGE_UI_OPERATE_PROTOCAL:
                String protocal = (String) msg.obj;
                if (mTalkServicePresentor != null) {
                    mTalkServicePresentor.setProtocal(protocal);
                }
                break;
            case SessionPreference.MESSAGE_HIDE_WINDOW:
                mContext.hide();
                break;
            case SessionPreference.MESSAGE_MOREFUNCTION_PROTOCAL:
                showMoreFunction();
                break;
            }
        }

    };

    /*
     * private IFunctionListener mFunctionListener = new IFunctionListener() {
     * 
     * @Override public void onFunctionItemClick(String action, View view) {
     * LogUtil.d(TAG, "action: " + action);
     * 
     * mTalkServicePresentor.stopTTS(); cancelTalk();
     * 
     * String[] array = null; if (action.equals(SessionPreference.DOMAIN_SMS)) {
     * array = KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_sms); } else if
     * (action.equals(SessionPreference.DOMAIN_CALL)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_call);
     * } else if (action.equals(SessionPreference.DOMAIN_APP)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_app); }
     * else if (action.equals(SessionPreference.DOMAIN_WEATHER)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_weather); } else if
     * (action.equals(SessionPreference.DOMAIN_SEARCH)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_search); } else if
     * (action.equals(SessionPreference.DOMAIN_REMINDER)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_memo);
     * } else if (action.equals(SessionPreference.DOMAIN_WEIBO)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_weibo);
     * } else if (action.equals(SessionPreference.DOMAIN_ROUTE)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_route);
     * } else if (action.equals(SessionPreference.DOMAIN_MUSIC)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_music);
     * } else if (action.equals(SessionPreference.DOMAIN_FLIGHT)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_flight); } else if
     * (action.equals(SessionPreference.DOMAIN_TRAIN)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_train);
     * } else if (action.equals(SessionPreference.DOMAIN_STOCK)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_stock);
     * } else if (action.equals(SessionPreference.DOMAIN_TV)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_tv); }
     * else if (action.equals(SessionPreference.DOMAIN_NEARBY_SEARCH)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_nearby); } else if
     * (action.equals(SessionPreference.DOMAIN_SITEMAP)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_sitemap); } else if
     * (action.equals(SessionPreference.DOMAIN_YELLOWPAGE)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_yellowpage); } else if
     * (action.equals(SessionPreference.DOMAIN_NEWS)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_news);
     * } else if (action.equals(SessionPreference.DOMAIN_COOKBOOK)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_cookbook); } else if
     * (action.equals(SessionPreference.DOMAIN_TRANSLATION)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_translation); } else if
     * (action.equals(SessionPreference.DOMAIN_VIDEO)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_video);
     * } else if (action.equals(SessionPreference.DOMAIN_MOVIE)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_movie);
     * } else if (action.equals(SessionPreference.DOMAIN_NOVEL)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_novel);
     * } else if (action.equals(SessionPreference.DOMAIN_CONTACT)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_contact); } else if
     * (action.equals(SessionPreference.DOMAIN_SETTING)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_setting); } else if
     * (action.equals(SessionPreference.DOMAIN_CHAT)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_talk);
     * } else if (action.equals(SessionPreference.DOMAIN_MOBILE_CONTROL)) {
     * array = KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_mobile); } else if
     * (action.equals(SessionPreference.DOMAIN_CHANNEL_SWITCH)) { array =
     * KnowledgeBase.getStringArray(mContext,
     * Res.array.function_example_channel_switch); } else if
     * (action.equals(SessionPreference.DOMAIN_SHOP)) { array =
     * KnowledgeBase.getStringArray(mContext, Res.array.function_example_shop);
     * } else { return; }
     * 
     * LayoutInflater mInflater = LayoutInflater.from(mContext); LinearLayout v
     * = (LinearLayout) mInflater.inflate(
     * Res.layout.function_show_dialog_content_view, null);
     * 
     * mPopupWindow = new PopupWindow(v, LayoutParams.WRAP_CONTENT,
     * LayoutParams.WRAP_CONTENT); int[] location = new int[2];
     * view.getLocationOnScreen(location); int x = location[0]; int y =
     * location[1];
     * 
     * WindowManager windowManager = (WindowManager) mContext
     * .getSystemService(Context.WINDOW_SERVICE); Display display =
     * windowManager.getDefaultDisplay(); boolean isUp = (y <
     * display.getHeight() / 2); if (isUp) {
     * v.setBackgroundResource(Res.drawable.ic_popup_bg_up); } else {
     * v.setBackgroundResource(Res.drawable.ic_popup_bg_down); } LinearLayout
     * container = (LinearLayout) v .findViewById(Res.id.container); for (int i
     * = 0; i < array.length; i++) { String s = array[i]; TextView text =
     * (TextView) mInflater.inflate( Res.layout.text_view_function_example,
     * null); text.setText(s); container.addView(text); if (i != array.length -
     * 1) { LogUtil.d(TAG, "init FunctionView: " + s); ImageView image =
     * (ImageView) mInflater.inflate( Res.layout.image_view_function_example,
     * null); container.addView(image); } }
     * mPopupWindow.setBackgroundDrawable(new ColorDrawable(
     * Color.TRANSPARENT)); mPopupWindow.setFocusable(true);
     * mPopupWindow.setOutsideTouchable(true);
     * mPopupWindow.getContentView().setFocusableInTouchMode(true);
     * mPopupWindow.getContentView().setOnKeyListener( new View.OnKeyListener()
     * {
     * 
     * @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if
     * (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getRepeatCount() == 0
     * && event.getAction() == KeyEvent.ACTION_DOWN) { mPopupWindow.dismiss();
     * return true; } return false; } });
     * 
     * LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
     * LayoutParams.WRAP_CONTENT); v.setLayoutParams(lp);
     * v.measure(v.getWidth(), v.getHeight()); int xPos = x + (view.getWidth() -
     * v.getMeasuredWidth()) / 2; if (isUp) { mPopupWindow.showAtLocation(view,
     * Gravity.NO_GRAVITY, xPos, y + view.getHeight()); } else {
     * mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, xPos, y -
     * v.getMeasuredHeight()); } } };
     */

    public void hidePopup() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    private ITalkServicePresentorListener mTalkServicePresentorListener = new ITalkServicePresentorListener() {

        @Override
        public void onTalkStop() {
            SessionManager.this.onTalkStop();
        }

        @Override
        public void onTalkStart() {
            SessionManager.this.onTalkStart();
        }

        @Override
        public void onSessionProtocal(String protocal) {
            SessionManager.this.onSessionProtocal(protocal);
        }

        @Override
        public void onTalkInitDone() {
            SessionManager.this.onTalkInitDone();
        }

        @Override
        public void onTalkCancel() {
            SessionManager.this.onTalkCancel();
        }

        // @Override
        // public void onBuffer() {
        // SessionManager.this.onBuffer();
        // }
        //
        // @Override
        // public void onPlayBegin() {
        // SessionManager.this.onPlayBegin();
        // }
        //
        // @Override
        // public void onPlayEnd() {
        // SessionManager.this.onPlayEnd();
        // }

        @Override
        public void onConnectClient() {
            SessionManager.this.onConnectClient();
        }

        @Override
        public void onDisconnectClient() {
            SessionManager.this.onDisconnectClient();
        }

        @Override
        public void onTalkRecordingStart() {
            SessionManager.this.onTalkRecordingStart();
        }

        @Override
        public void onConnectivityChanged() {
            SessionManager.this.onConnectivityChanged();
        }

        @Override
        public void onUpdateVolume(int volume) {
            SessionManager.this.onUpdateVolume(volume);
        }

        // @Override
        // public void onCancel() {
        // SessionManager.this.onPlayCancel();
        // }
    };

    public SessionManager(WindowService context, ViewFlipper viewFlipper) {
        mContext = context;
        // mViewFlipper = viewFlipper;
        init();

    }

    private void init() {
        //
        // mFunctionViewContainer = (SessionContainer)
        // mViewFlipper.getChildAt(0);
        // mSessionViewContainer = (SessionContainer)
        // mViewFlipper.getChildAt(1);
        mTalkServicePresentor = new TalkServicePresentor(mContext, mTalkServicePresentorListener);
        micFloatView = new GloblFloatView(mContext);
    }

    private void showMoreFunction() {
        // mViewFlipper.setDisplayedChild(0);
    }

    public void setSessionListener(ISessionManagerListener listener) {
        mListener = listener;
    }

    public void startTalk() {
        LogUtil.d(TAG, "startTalk");
        mTalkServicePresentor.startTalk();
    }

    public void stopTalk() {
        LogUtil.d(TAG, "stopTalk");
        mTalkServicePresentor.stopTalk();
    }

    public void startByControlButton() {
        LogUtil.d(TAG, "startByControlButton");
        startTalk();
    }

    public void stopByControlButton() {
        LogUtil.d(TAG, "stopByControlButton");
        stopTalk();
    }

    public void cancelTalk() {
        LogUtil.d(TAG, "cancelTalk");
        mTalkServicePresentor.cancelTalk();
    }

    private void waitForRecognitionResult() {
        LogUtil.d(TAG, "waitForRecognitionResult");
        micFloatView.updateVoiceView(VoiceMode.MODE_RECOGNISING);
    }

    public void resetTalk(VoiceMode mode) {
    }

    public void onPause() {
        LogUtil.d(TAG, "onPause");
        hidePopup();
        // PlayerEngine.getInstance().pause();
        mTalkServicePresentor.stopTTS();
        resetTalk(VoiceMode.MODE_DEFAULT);

        mTalkServicePresentor.onPause();
    }

    public void stopTTS() {
        mTalkServicePresentor.stopTTS();
        // if (mCurrentSession != null) {
        // mCurrentSession = null;
        // }
    }

    public boolean getPopupWindowIsShowing() {
        if (mPopupWindow != null) {
            return mPopupWindow.isShowing();
        } else {
            return false;
        }
    }

    public void onResume() {
        LogUtil.d(TAG, "onResume");
        mTalkServicePresentor.onResume();
        updateFunctionView(Network.hasNetWorkConnect());
        mNeedAutoStart = true;
    }

    public void onDestroy() {
        LogUtil.d(TAG, "onDestroy");
        // if (mCurrentSession != null) {
        // mCurrentSession = null;
        // if (mTalkServicePresentor != null) {
        // mTalkServicePresentor.setProtocal(BACK_PROTOCAL);
        // }
        // }
        // mSessionViewContainer.removeAllSessionViews();
        mDelayTaskArray.clear();
        mTalkServicePresentor.onDestroy();
    }

    public boolean onBackPressed() {
        LogUtil.d(TAG, "onBackPressed");
        boolean result = false;
        mTalkServicePresentor.stopTTS();
        // if (mCurrentSession != null) {
        // result = true;
        // }

        if (!isFunctionViewShown()) {
            updateFunctionView(Network.hasNetWorkConnect());
            result = true;
        }

        return result;
    }

    private void updateFunctionView(boolean hasNetwork) {
        // LogUtil.d(TAG, "updateFunctionView:hasNetwork " + hasNetwork);
        // mFunctionViewContainer.removeAllSessionViews();
        // getFunctionView().initFunctionViews(hasNetwork);
        // String ttsString = KnowledgeMode.getKnowledgeAnswer(mContext,
        // KnowledgeMode.KNOWLEDGE_STAGE_HELP);
        // mFunctionViewContainer.addAnswerView(ttsString);
        // View v = getFunctionView();
        // SessionContainer.addViewNow(v.hashCode());
        // LogUtil.d(TAG, "updateFunctionView:"
        // + ((FunctionContainer) v).getChildAt(1).requestFocus());
        // mFunctionViewContainer.addSessionView(v, false);
    }

    private String mQuestion;

    public void onSessionProtocal(String protocal) {
        String mProtocal = "";
        JSONObject obj = JsonTool.parseToJSONObject(protocal);
        if (obj != null) {
            JSONObject dataObj = BaseSession.getJSONObject(obj, SessionPreference.KEY_DATA);
            String message = BaseSession.getJsonValue(dataObj, SessionPreference.KEY_QUESTION);
            if (!TextUtils.isEmpty(message)) {
                mQuestion = message;
            }
            mProtocal = message;
        }
        String type = JsonTool.getJsonValue(obj, SessionPreference.KEY_TYPE, "");
        if (SessionPreference.VALUE_TYPE_WAITING.equals(type) || TextUtils.isEmpty(type)) {
            Message msg = new Message();
            msg.what = 1;
            msg.obj = protocal;
            mHandler.sendMessageDelayed(msg, 800);
            return;
        }

        // not good, fix me!!!

        mQuestion = mQuestion.replaceAll("([^\u4e00-\u9fa5a-zA-Z0-9])", "");
        try {
            if (mIVuiVoiceCallBack != null && !mIVuiVoiceCallBack.onVoiceMessage(mQuestion))
                customAction(mContext, mQuestion);
        } catch (RemoteException e) {
            customAction(mContext, mQuestion);
        }
        // }
        // if (!TextUtils.isEmpty(mProtocal)) {
        // micFloatView.setProtocal(mProtocal);
        // micFloatView.updateVoiceView(VoiceMode.MODE_PROTOCAL);
        // }
        // Message msg = new Message();
        // msg.what = 0;
        // msg.obj = protocal;
        // mHandler.sendMessageDelayed(msg, 800);
    }

    IVuiVoiceCallBack mIVuiVoiceCallBack;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:
                micFloatView.hide();
                mContext.show();
                // MainActivity.mVoiceKeyFlag = false;
                createSession((String) msg.obj);
                break;
            case 1:
                micFloatView.hide();
                // mContext.show();
                // MainActivity.mVoiceKeyFlag = false;
                break;
            default:
                break;
            }

        }
    };

    private void onTalkInitDone() {
        LogUtil.d(TAG, "onTalkServiceInitDone mNeedAutoStart=" + mNeedAutoStart);
        Log.d("SHOW_TIME", "SessionManager:TALK SERVICE INIT DONE");

        if (mNeedAutoStart) {
            mNeedAutoStart = false;
        }
    }

    private void onConnectivityChanged() {
        LogUtil.d(TAG, "onConnectivityChanged");
        boolean hasNetwork = Network.hasNetWorkConnect();
        // if (getFunctionView().getParent() != null) {
        // updateFunctionView(hasNetwork);
        // }

        if (mListener != null) {
            mListener.onConnectivityChanged(hasNetwork);
        }
    }

    public void onTalkRecordingStart() {
        LogUtil.d(TAG, "onTalkRecordingStart");
        micFloatView.updateVoiceView(VoiceMode.MODE_RECORDING);
    }

    public void onBuffer() {

    }

    public void onPlayBegin() {

    }

    public void onPlayEnd() {
        LogUtil.d(TAG, "onPlayEnd");
        int value = mDelayTaskArray.pop(TASK_DELAY_KEY_TTS_END);
        if (mListener != null && value != 0) {
            handleDelayTask(value);
        }
    }

    private void handleDelayTask(int value) {
        switch (value) {
        case TASK_DELAY_VALUE_RESET_TIMER:
            if (mListener != null) {
                mListener.onResetTimer();
            }
            break;
        }
    }

    private void createSession(String protocal) {
        /*
         * LogUtil.d(TAG, "createSession:" + protocal); JSONObject obj =
         * JsonTool.parseToJSONObject(protocal); BaseSession base = null;
         * mContext.show(); if (obj != null) { String sessionStatus =
         * JsonTool.getJsonValue(obj, SessionPreference.KEY_DOMAIN, "");
         * 
         * if (SessionPreference.VALUE_SESSION_BENGIN.equals(sessionStatus)) {
         * mSessionViewContainer.removeAllSessionViews(); }
         * 
         * String type = JsonTool.getJsonValue(obj, SessionPreference.KEY_TYPE,
         * ""); LogUtil.d(TAG, "type : " + type); if
         * (SessionPreference.VALUE_TYPE_INPUT_CONTENT_WEIBO.equals(type)) { if
         * (mCurrentSession != null && mCurrentSession instanceof
         * WeiBoInputShowSession) { base = mCurrentSession; } else { base = new
         * WeiBoInputShowSession(mContext, mSessionManagerHandler); } } else if
         * (SessionPreference.VALUE_TYPE_WEIBO_OK.equals(type)) { // base = new
         * WeiBoShowSession(mContext, // mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_WAITING.equals(type)) { if
         * (mCurrentSession != null && mCurrentSession instanceof
         * WeiBoInputShowSession) { base = mCurrentSession; } else { base = new
         * WaitingSession(mContext, mSessionManagerHandler); } } else if
         * (SessionPreference.VALUE_TYPE_WEATHER_SHOW.equals(type)) { base = new
         * WeatherShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_WEB_SHOW.equals(type)) { base = new
         * WebShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_TRANSLATION_SHOW .equals(type)) { base
         * = new TranslationShowSession(mContext, mSessionManagerHandler); }
         * else if (SessionPreference.VALUE_TYPE_STOCK_SHOW.equals(type)) { base
         * = new StockShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_MUSIC_SHOW.equals(type)) { base = new
         * MusicShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_PROG_RECOMMEND.equals(type)) { base =
         * new ProgRecommendSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_PROG_SEARCH_RESULT .equals(type)) {
         * base = new ProgSearchResultSession(mContext, mSessionManagerHandler);
         * } else if (SessionPreference.VALUE_TYPE_CHANNEL_PROG_LIST
         * .equals(type)) { base = new ChannelProgListSession(mContext,
         * mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_APP_LAUNCH.equals(type)) { base = new
         * AppLaunchSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_APP_UNINSTALL.equals(type)) { base =
         * new AppUninstallSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_SETTING.equals(type)) { base = new
         * SettingSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_TALK_SHOW.equals(type) ||
         * SessionPreference.VALUE_TYPE_INPUT_CONTACT.equals(type)) { base = new
         * TalkShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_ERROR_SHOW.equals(type)) { base = new
         * ErrorShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_UI_HANDLE_SHOW.equals(type)) { base =
         * new VideoShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_TYPE_APP_EXIT.equals(type)) { base = new
         * AppExitSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.VALUE_UI_PROTOCAL_SHOW.equals(type)) { String
         * originType = null; try { originType = obj
         * .getString(SessionPreference.KEY_ORIGIN_TYPE); } catch (JSONException
         * e) { e.printStackTrace(); } if
         * (SessionPreference.DOMAIN_VIDEO.equals(originType)) { base = new
         * VideoShowSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.DOMAIN_LOCAL.equals(originType)) { base = new
         * MoreFunctionSession(mContext, mSessionManagerHandler); } else if
         * (SessionPreference.DOMAIN_ERROR.equals(originType)) { base = new
         * UnsupportShowSession(mContext, mSessionManagerHandler); } } else if
         * (SessionPreference.VALUE_TYPE_CHANNEL_SWITCH_SHOW .equals(type)) {
         * base = new ChannelSwitchSession(mContext, mSessionManagerHandler); }
         * else if (SessionPreference.VALUE_TYPE_SHOP_SHOW.equals(type)) { base
         * = new ShopShowSession(mContext, mSessionManagerHandler); } } if (base
         * != null) { mSessionViewContainer.clearTemporaryViews();
         * mCurrentSession = base; mCurrentSession.putProtocol(obj); } else {
         * JSONObject dataObj = BaseSession.getJSONObject(obj,
         * SessionPreference.KEY_DATA); String message =
         * BaseSession.getJsonValue(dataObj, SessionPreference.KEY_QUESTION);
         * String ttString = null; if (TextUtils.isEmpty(message)) {
         * mSessionViewContainer.clearTemporaryViews(); ttString =
         * KnowledgeMode.getKnowledgeAnswer(mContext,
         * KnowledgeMode.KNOWLEDGE_STAGE_NO_INPUT); } else {
         * mSessionViewContainer.addQustionView(message); ttString =
         * KnowledgeMode.getRecognitionNoResultAnswer(mContext, message); }
         * addAnswerText(ttString); playTTS(ttString); } if
         * (mViewFlipper.getDisplayedChild() != 1) {
         * mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext,
         * Res.anim.slide_in_right));
         * mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext,
         * Res.anim.slide_out_left)); mViewFlipper.setDisplayedChild(1);
         * ((SessionContainer) mViewFlipper.getChildAt(1)).requestSuperFocus();
         * }
         */
    }

    private void addAnswerText(String text) {
        Message msg = new Message();
        msg.what = SessionPreference.MESSAGE_ADD_ANSWER_TEXT;
        msg.obj = text;
        mSessionManagerHandler.sendMessage(msg);
    }

    private void playTTS(String text) {
        Message tts = mSessionManagerHandler.obtainMessage(SessionPreference.MESSAGE_REQUEST_PLAY_TTS);
        tts.obj = text;
        mSessionManagerHandler.sendMessage(tts);
    }

    // public FunctionContainer getFunctionView() {
    // LogUtil.d(TAG, "getFunctionView");
    // if (mFunctionContainer == null) {
    // mFunctionContainer = new FunctionContainer(mContext);
    // mFunctionContainer.setFunctionListener(mFunctionListener);
    // }
    // return mFunctionContainer;
    // }

    public void onFunctionClick() {
        onBackPressed();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if (mCurrentSession != null) {
        // mCurrentSession.onActivityResult(requestCode, resultCode, data);
        // }
    }

    private boolean isFunctionViewShown() {
        // if (mFunctionContainer == null
        // || mFunctionContainer.getParent() == null) {
        // return false;
        // }
        return true;
    }

    public static interface ISessionManagerListener {
        void onConnectivityChanged(boolean hasNetwork);

        // void onMusicSearchDone(PlayList playList);

        void onResetTimer();

        void onCancelTimer();

        void onConnectClient();

        void onDisconnectClient();
    }

    private static class DelayTaskArray extends SparseIntArray {
        public int pop(int key) {
            int value = get(key);
            delete(key);
            return value;
        }
    }

    private void onTalkStart() {
        LogUtil.d(TAG, "onTalkStart");
        // RomControl.enterControl(mContext, RomControl.START_ASSISTANT);
        micFloatView.updateVoiceView(VoiceMode.MODE_RECORDINGINIT);
        micFloatView.show();
        // PlayerEngine.releaseIfPlaying();
        mTalkServicePresentor.stopTTS();
        mContext.hide();
    }

    private void onUpdateVolume(int volume) {
        micFloatView.updateVolume(volume);
    }

    private void onTalkStop() {
        LogUtil.d(TAG, "onTalkStop");
        waitForRecognitionResult();
    }

    private void onTalkCancel() {
        LogUtil.d(TAG, "onTalkCancel");

        micFloatView.updateVoiceView(VoiceMode.MODE_DEFAULT);
        micFloatView.hide();

        // MainActivity.mVoiceKeyFlag = false;
        resetTalk(VoiceMode.MODE_DEFAULT);
    }

    private void onPlayCancel() {

    }

    public void onConnectClient() {
        if (mListener != null) {
            mListener.onConnectClient();
        }
    }

    public void onDisconnectClient() {
        if (mListener != null) {
            mListener.onDisconnectClient();
        }
    }

    public static String getLiveId(Context ctx, String what, boolean fromVoice) {
        Cursor c = ctx.getContentResolver().query(Uri.parse("content://com.myvst.v2.provider/channel_info"),
                new String[] { "vid", "num", "vname" }, null, null, null);
        if (c == null) {
            return null;
        }

        try {
            Locale locale = Locale.getDefault();
            while (c.moveToNext()) {
                String name = fromVoice ? c.getString(2).toLowerCase(Locale.getDefault()) : c.getString(1).toLowerCase(
                        locale);
                if (fromVoice) {
                    if (name.contains(what) || what.contains(name)) {
                        return c.getString(0);
                    }
                } else {
                    if (name.equals(what)) {
                        return c.getString(0);
                    }
                }
            }
        } finally {
            c.close();
        }
        return null;
    }

    public static Intent getLiveIntent(Context ctx, String what) {
        try {
            if ("直播".equals(what) || what.contains("看直播")) {
                return new Intent("myvst.intent.action.LivePlayer").setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
        } catch (Exception e) {
        }
        String vid = getLiveId(ctx, what, true);
        if (TextUtils.isEmpty(vid)) {
            return null;
        }
        return getLiveIntent(vid);
    }

    public static Intent getLiveIntent(String vid) {
        return new Intent("myvst.intent.action.LivePlayer").setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .putExtra("isCustom", 0).putExtra("vid", vid);
    }

    public static Intent getVstIntent(Context ctx, String what) {
        Intent intent = getLiveIntent(ctx, what);
        if (intent == null)
            return new Intent("myvst.intent.action.SearchActivity").putExtra("search_word", what)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        return intent;
    }

    public static void customAction(Context ctx, String what) {
        if (TextUtils.isEmpty(what))
            return;
        customAction(ctx, getVstIntent(ctx, what));
    }

    public static void customAction(Context ctx, Intent intent) {
        try {
            ctx.startActivity(intent);
        } catch (Exception e) {

        }
    }

    public void setVoiceMessageCallback(cn.yunzhisheng.vui.assistant.tv.IVuiVoiceCallBack ck) {
        mIVuiVoiceCallBack = ck;
    }
}
